﻿using System.IO.Ports;

namespace Proxy
{
    public class SerialPortsHelper
    {
        public static SerialPort SerialPort = null;

        public string[] GetPortNames()
        {
            return SerialPort.GetPortNames();
        }

        public static SerialPort OpenClosePort(string comName, int baud)
        {
            if (SerialPort == null || !SerialPort.IsOpen)
            {
                SerialPort = new SerialPort();
                //串口名称
                SerialPort.PortName = comName;
                //波特率
                SerialPort.BaudRate = baud;
                //数据位
                SerialPort.DataBits = 8;
                //停止位
                SerialPort.StopBits = StopBits.One;
                //校验位
                SerialPort.Parity = Parity.None;
                //打开串口
                SerialPort.Open();
                //数据接收事件
                //SerialPort.DataReceived += SerialPort_DataReceived;
                return SerialPort;
            }
            else
            {
                SerialPort.Close();
                return SerialPort;
            }
        }

        private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort _SerialPort = (SerialPort)sender;

            int _bytesToRead = _SerialPort.BytesToRead;
            byte[] recvData = new byte[_bytesToRead];

            _SerialPort.Read(recvData, 0, recvData.Length);
        }

        public static bool SendData(byte[] data)
        {
            if (SerialPort != null && SerialPort.IsOpen)
            {
                SerialPort.Write(data, 0, data.Length);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}